#include "server.hpp"
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
void Usage()
{
    std::cout << "usage: ./client server_ip server_port" << std::endl;
}

int main(int argc, char *argv[])
{
    //./client server_ip sever_port
    if (argc != 2)
    {
        Usage();
    }
    // 创建套接字：
    int socketfd = socket(AF_INET, SOCK_STREAM, 0);
    if (socketfd < 0)
    {
        std::cout << "socket fail!" << std::endl;
        exit(1);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    // 不需要显式半绑定ip与端口
    // 直接进行connect:
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    inet_pton(AF_INET, server_ip.c_str(), &server.sin_addr);

    // 与对应服务器进行连接：
    socklen_t len = sizeof(server);
    int ret = connect(socketfd, (const struct sockaddr *)&server, len);
    if (ret < 0)
    {
        std::cout << "connect fail!" << std::endl;
        exit(2);
    }
    std::cout << "connect success!" << std::endl;
    // connect成功后不会产生新的套接字，我们通过原有的socketfd与服务器进行数据通信：
    while (1)
    {
        std::cout<<"Please Enter:"<<std::endl;
        std::string line;
        getline(std::cin,line);
        int ret=write(socketfd,line.c_str(),line.size());
        if(ret>0)
        {
            //写入成功，接受来自服务器的echo消息：
            char buffer[1024];
            int n=read(socketfd,buffer,sizeof(buffer)-1);
            if(n>0)
            {
                buffer[n]='0';
                std::cout<<buffer<<std::endl;
            }
            else
            {
                break;
            }
        }
        else
        break;
    }
}